<?php

// $Id: user_activity_type_dbc.class.php 1571 2009-01-13 13:08:33Z ogrebg $

require_once(TANGRA_MAIN_DIR.'interfaces/i_db_storable.class.php');


require_once('user_activity_type.class.php');


class User_Activity_Type_DBC extends User_Activity_Type {
	private $db_table_prefix;

	function __construct($db_table_prefix = '') {
		$this->set_db_table_prefix($db_table_prefix);
	}


	public function set_db_table_prefix($db_table_prefix) {
		$this->db_table_prefix = $db_table_prefix;
	}


	public function get_db_table_prefix() {
		return $this->db_table_prefix;
	}


	public function save(DB_Connection $dbc) {
		$ret = false;

		if ($this->get_id()) {
			$ret = $this->update($dbc);
		} else {
			$ret = $this->insert($dbc);
		}

		return $ret;
	}


	public function load_by_id(DB_Connection $dbc, $id) {
		$ret = false;

		$sql = "select description, "
						."hid "
					."from ".$this->get_db_table_prefix()."user_activity_types where id = $id";

		$rez = $dbc->execute($sql);

		if (!$rez->is_eof()) {
			$rez_obj = $rez->fetch_object();
			$this->set_id($id);
			$this->set_description(stripslashes($rez_obj->DESCRIPTION));
			$this->set_hid(stripslashes($rez_obj->HID));

			$ret = $id;
		}

		return $ret;
	}


	protected function insert(DB_Connection $dbc) {
		$ret = false;

		$id = $dbc->generate_id($this->get_db_table_prefix()."user_activity_types_seq");
		if ($id) {

			$description = addslashes($this->get_description());
			$hid = addslashes($this->get_hid());

			$sql = "insert into ".$this->get_db_table_prefix()."user_activity_types"
								."(id, "
								."description, "
								."hid "
								.") "
							."values ("
								."$id, "
								."$description, "
								."$hid "
								.")";
			$dbc->execute($sql);

			$ret = $id;
		} else {
			throw new TE_Exception("ID not generated - ".$this->get_db_table_prefix()."user_activity_types_seq");
		}

		return $ret;
	}


	protected function update(DB_Connection $dbc) {
		$cookie = $this->get_cookie();
		$user = $this->get_user();

		$user = $this->get_user();
		$type = $this->get_type();

		$sql = "update ".$this->get_db_table_prefix()."user_activity_types set "
							."user = $user, "
							."type = $type "
					."where id = ".$this->get_id();

		$dbc->execute($sql);

		return $this->get_id();
	}


	public function load_by_hid(DB_Connection $dbc, $hid) {
		$hid = addslashes($hid);
		$ret = false;

		$sql = "select id from ".$this->get_db_table_prefix()."user_activity_types where hid = '$hid'";
		$rez = $dbc->execute($sql);

		if (!$rez->is_eof()) {
			$rez_obj = $rez->fetch_object();
			$ret = $this->load_by_id($dbc, $rez_obj->ID);
		}

		return $ret;
	}


	public static function delete(DB_Connection $dbc, $id, $prefix = '') {
		tangra_if_not_int_throw_e($id);
		$sql = "delete from ".$this->get_db_table_prefix()."user_activity_types where id = $id";
		$dbc->execute($sql);
	}

}